package org.esprit.ocm.client.ui.one;

import java.util.List;

import org.esprit.ocm.client.model.oca.datasource.VnetLocalDS;
import org.esprit.ocm.client.rpc.oca.VirtualNetworkOcaService;
import org.esprit.ocm.client.rpc.oca.VirtualNetworkOcaServiceAsync;
import org.esprit.ocm.dto.impl.AwsCredentialsDto;
import org.esprit.ocm.dto.impl.ServerDto;
import org.esprit.ocm.dto.impl.UserDto;
import org.esprit.ocm.model.oca.VnetOca;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.events.RecordClickEvent;
import com.smartgwt.client.widgets.grid.events.RecordClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.viewer.DetailViewer;
import com.smartgwt.client.widgets.viewer.DetailViewerField;

public class VnetZone extends SectionStack {

	private final VirtualNetworkOcaServiceAsync	vnetOcaService	= GWT.create(VirtualNetworkOcaService.class);

	private DataSource							ds;
	private ListGrid							grid;
	private DetailViewer						details;
	private DetailViewer						detailsLeases;
	private DetailViewer						detailsTemplate;

	public VnetZone(final ServerDto server, final AwsCredentialsDto credentials, final UserDto user) {

		getData(server, credentials);

		// creer imageSection
		SectionStackSection networkSection = new SectionStackSection("Virtual Networks List");
		networkSection.setExpanded(true);
		addSection(networkSection);

		// creer imageGrid
		grid = new ListGrid();
		setVisibilityMode(VisibilityMode.MULTIPLE);
		setHeaderHeight(20);
		// instanceGrid.setShowFilterEditor(true);
		grid.setFilterOnKeypress(true);
		grid.setAutoFetchData(true);

		// creer imagetoolstrip
		ToolStrip networkGridToolStrip = new ToolStrip();
		networkGridToolStrip.setWidth100();
		networkGridToolStrip.addFill();

		// ajouter toolstrip a instanceSection
		networkSection.addItem(networkGridToolStrip);

		// creer filterButton
		final Button filterButton = new Button("Filter");
		filterButton.setShowRollOver(true);
		filterButton.setShowDown(true);
		filterButton.setIcon("filter.png");
		filterButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
				filterButton.addClickHandler(new ClickHandler() {

					public void onClick(ClickEvent event) {
						grid.setShowFilterEditor(false);

					}
				});
			}
		});

		final Button vmButton = new Button("New Vnet");
		vmButton.setShowRollOver(true);
		vmButton.setShowDown(true);
		vmButton.setIcon("add.png");
		vmButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				CreateVN createVN = new CreateVN(server, credentials, user);
				createVN.show();
			}
		});

		final Button refreshButton = new Button("Refresh");
		refreshButton.setShowRollOver(true);
		refreshButton.setShowDown(true);
		refreshButton.setIcon("interact.png");
		refreshButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SC.say("Refreshed");
				ds.destroy();
				getData(server, credentials);
				grid.redraw();
			}
		});

		final Button publishButton = new Button("Publish");
		publishButton.setShowRollOver(true);
		publishButton.setShowDown(true);
		publishButton.setIcon("publish.png");
		publishButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int id = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				vnetOcaService.publish(secret, endpoint, id, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		final Button unpublishButton = new Button("Unpublish");
		unpublishButton.setShowRollOver(true);
		unpublishButton.setShowDown(true);
		unpublishButton.setIcon("unpublish.png");
		unpublishButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int id = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				vnetOcaService.unpublish(secret, endpoint, id, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		final Button deleteButton = new Button("Delete");
		deleteButton.setShowRollOver(true);
		deleteButton.setShowDown(true);
		deleteButton.setIcon("remove.png");
		deleteButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
				String endpoint = server.getIpServer();

				int id = Integer.parseInt(grid.getSelectedRecord().getAttribute("id"));

				vnetOcaService.delete(secret, endpoint, id, new AsyncCallback<String>() {

					public void onSuccess(String s) {
						SC.warn(s);
						ds.destroy();
						getData(server, credentials);
						grid.redraw();
					}

					public void onFailure(Throwable caught) {

					}
				});
			}
		});

		Img filter = new Img("filter.png", 15, 15);

		// creer filterButton
		final Button filterButtonOn = new Button("On");
		filterButtonOn.setWidth(25);
		filterButtonOn.setHeight(20);
		filterButtonOn.setShowRollOver(true);
		filterButtonOn.setShowDown(true);
		// filterButtonOn.setIcon("filter.png");
		filterButtonOn.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(true);
				grid.setFilterOnKeypress(true);
			}
		});
		// creer filterButton
		final Button filterButtonOff = new Button("Off");
		filterButtonOff.setWidth(25);
		filterButtonOff.setHeight(20);
		filterButtonOff.setShowRollOver(true);
		filterButtonOff.setShowDown(true);
		// filterButtonOff.setIcon("filter.png");
		filterButtonOff.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {

				grid.setShowFilterEditor(false);
				grid.setFilterOnKeypress(false);
			}
		});

		// ajouter le bouton
		networkGridToolStrip.addMember(vmButton);
		networkGridToolStrip.addMember(deleteButton);
		networkGridToolStrip.addSpacer(30);
		networkGridToolStrip.addMember(publishButton);
		networkGridToolStrip.addMember(unpublishButton);
		networkGridToolStrip.addSpacer(30);
		networkGridToolStrip.addMember(refreshButton);
		networkGridToolStrip.addSpacer(10);
		networkGridToolStrip.addMember(filter);
		networkGridToolStrip.addSpacer(2);
		networkGridToolStrip.addMember(filterButtonOn);
		networkGridToolStrip.addMember(filterButtonOff);
		networkGridToolStrip.addSpacer(5);

		// ajouter instanceGrid a instanceSection
		networkSection.addItem(grid);

		// creer DetailinstanceSection

		details = new DetailViewer();
		details.setWidth100();
		details.setMargin(15);
		details.setEmptyMessage("Select something to view its details");

		detailsLeases = new DetailViewer();
		detailsLeases.setWidth100();
		detailsLeases.setMargin(15);
		detailsLeases.setEmptyMessage("Select something to view its details");

		detailsTemplate = new DetailViewer();
		detailsTemplate.setWidth100();
		detailsTemplate.setMargin(15);
		detailsTemplate.setEmptyMessage("Select something to view its details");

		grid.addRecordClickHandler(new RecordClickHandler() {

			public void onRecordClick(RecordClickEvent event) {

				details.setData(new Record[] { event.getRecord() });
				detailsLeases.setData(new Record[] { event.getRecord() });
				detailsTemplate.setData(new Record[] { event.getRecord() });

			}
		});

		HLayout viewDetail = new HLayout();
		viewDetail.setHeight("30%");
		viewDetail.setPadding(5);

		// viewDetail.addMember(details);
		viewDetail.addMember(detailsTemplate);
		viewDetail.addMember(detailsLeases);

		SectionStackSection networkDetailSection = new SectionStackSection("Virtual Network Detail");
		networkDetailSection.setExpanded(true);
		networkDetailSection.addItem(viewDetail);
		addSection(networkDetailSection);

		draw();
	}

	private void getData(ServerDto server, AwsCredentialsDto credentials) {

		String secret = credentials.getAwsAccessKeyId() + ":" + credentials.getSecretAccessKey();
		String endpoint = server.getIpServer();

		/**
		 * Possible values:
		 * <ul>
		 * <li><= -2: All Images</li>
		 * <li>-1: Connected user's Images</li>
		 * <li>>=0: UID User's VMs</li>
		 * </ul>
		 */
		// FIXME le graphique avec le filtre
		int filter = -2;
		vnetOcaService.listAll(secret, endpoint, filter, new AsyncCallback<List<VnetOca>>() {

			public void onSuccess(List<VnetOca> list) {

				for (VnetOca vnetOca : list) {
					System.out.println(vnetOca.getId());
				}

				ds = new DataSource();
				ds = VnetLocalDS.getInstance(list);

				grid.setDataSource(ds);
				details.setDataSource(ds);
				detailsTemplate.setDataSource(ds);
				detailsLeases.setDataSource(ds);

				ListGridField idField = new ListGridField("id", "id");
				ListGridField uid = new ListGridField("uid", "uid");
				ListGridField username = new ListGridField("username", "username");
				ListGridField name = new ListGridField("name", "name");
				ListGridField type = new ListGridField("type", "type");
				ListGridField bridge = new ListGridField("bridge", "bridge");
				ListGridField publicState = new ListGridField("publicState", "publicState");
				ListGridField total_leases = new ListGridField("total_leases", "total_leases");

				grid.setFields(idField, uid, username, name, type, bridge, publicState, total_leases);

				DetailViewerField template_bridge = new DetailViewerField("template_bridge", "template_bridge");
				DetailViewerField template_name = new DetailViewerField("template_name", "template_name");
				DetailViewerField template_type = new DetailViewerField("template_type", "template_type");
				DetailViewerField template_description = new DetailViewerField("template_description", "template_description");
				DetailViewerField template_network_address = new DetailViewerField("template_network_address", "template_network_address");
				DetailViewerField template_network_size = new DetailViewerField("template_network_size", "template_network_size");
				DetailViewerField template_leases_ip = new DetailViewerField("template_leases_ip", "template_leases_ip");

				detailsTemplate.setFields(template_bridge, template_name, template_type, template_description, template_network_address,
						template_network_size, template_leases_ip);

				DetailViewerField leases_lease_ip = new DetailViewerField("leases_lease_ip", "leases_lease_ip");
				DetailViewerField leases_lease_mac = new DetailViewerField("leases_lease_mac", "leases_lease_mac");
				DetailViewerField leases_lease_used = new DetailViewerField("leases_lease_used", "leases_lease_used");
				DetailViewerField leases_lease_vid = new DetailViewerField("leases_lease_vid", "leases_lease_vid");

				detailsLeases.setFields(leases_lease_ip, leases_lease_mac, leases_lease_used, leases_lease_vid);

			}

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub
			}
		});
	}

}
